import { Injectable } from '@nestjs/common';
import { CreateRecordCalcDto } from './dto/create-record_calc.dto';
// import { UpdateRecordCalcDto } from './dto/update-record_calc.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { RecordCalcEntity } from './entities/record_calc.entity';
import { Brackets, Repository } from 'typeorm';
import { CompanyService } from 'src/company/company.service';
import { UserEntity } from 'src/user/entities/user.entity';
import { ListRecordCalcDto } from './dto/list-record_calc.dto';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';

@Injectable()
export class RecordCalcService {
  constructor(
    @InjectRepository(RecordCalcEntity)
    private readonly recordCalcRepository: Repository<RecordCalcEntity>,
    private readonly companyService: CompanyService,
  ) {}
  async create(createRecordCalcDto: CreateRecordCalcDto, user: UserEntity) {
    // 验证company_id;
    if (
      createRecordCalcDto.company_id !== '' &&
      createRecordCalcDto.company_id !== '0'
    ) {
      const company = await this.companyService.findOne(
        createRecordCalcDto.company_id,
      );
      if (!company) throw new BusinessException('未找到公司');
      createRecordCalcDto.company_name = company.name;
    }

    return await this.recordCalcRepository.save({
      ...createRecordCalcDto,
      user_id: user.id,
    });
  }

  async findAll(searchParam: ListRecordCalcDto, user: UserEntity) {
    let company_ids: string[] = [];
    if (typeof searchParam['company_ids[]'] === 'string')
      company_ids = [searchParam['company_ids[]']];
    else if (searchParam['company_ids[]'] instanceof Array)
      company_ids = searchParam['company_ids[]'];

    const { current, size } = searchParam;
    const list = await this.recordCalcRepository
      .createQueryBuilder()
      .where({ user_id: user.id, is_delete: 0 })
      .andWhere(
        new Brackets((qb) => {
          if (!searchParam.remark) return qb;
          return qb.where('remark LIKE :remark', {
            remark: `%${searchParam.remark}%`,
          });
        }),
      )
      .andWhere(
        new Brackets((qb) => {
          if (company_ids.length === 0) return qb;
          qb.where('company_id IN (:...company_ids)', {
            company_ids,
          });
        }),
      )
      .orderBy('create_time', 'DESC')
      .skip((current - 1) * size)
      .take(size)
      .getManyAndCount();

    return {
      list: list[0],
      total: list[1],
      pages: Math.ceil(list[1] / size),
    };
  }

  // findOne(id: number) {
  //   return `This action returns a #${id} recordCalc`;
  // }

  // update(id: number, updateRecordCalcDto: UpdateRecordCalcDto) {
  //   return `This action updates a #${id} recordCalc`;
  // }
  async remove(id: string, user: UserEntity) {
    const record = await this.recordCalcRepository.findOne({
      where: { id, user_id: user.id, is_delete: 0 },
    });
    if (!record) throw new BusinessException('记录不存在');
    record.is_delete = 1;
    return await this.recordCalcRepository.save(record);
  }
}
